package com.zzj.ecology.system.service.impl.system;

import com.zzj.ecology.common.constant.GlobalConstant;
import com.zzj.ecology.common.constant.UserConstant;
import com.zzj.ecology.system.bean.system.*;
import com.zzj.ecology.system.dto.HttpResult;
import com.zzj.ecology.system.domain.Page;
import com.zzj.ecology.system.mapper.system.SysDeptMapper;
import com.zzj.ecology.system.mapper.system.SysPostMapper;
import com.zzj.ecology.system.mapper.system.SysRoleMapper;
import com.zzj.ecology.system.mapper.system.SysUserMapper;
import com.zzj.ecology.system.service.system.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName SysUserServiceImpl
 * @Description TODO
 * @Author zhijun zeng at 23:48 2020/4/1
 * @Version 1.0
 **/
@Service("sysUserService")
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl implements SysUserService {

    private final static Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 根据登录用户ID查询登录用户信息
     * @param userId
     * @return
     */
    public SysUser findById(Integer userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    /**
     * 根据登录用户名查询登录用户信息
     * @param username
     * @return
     */
    public SysUser findByUsername(String username) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);//查询条件
        criteria.andDeleteStatusEqualTo(UserConstant.DELETE_STATUS_NOT_DELETE);//账户未删除状态
        criteria.andUserStatusEqualTo(UserConstant.USER_STATUS_START);//账户启动状态
        // 设置 spring security 状态
        criteria.andAccountNotLockedEqualTo(true)//账户未锁定
                .andEnabledEqualTo(true)//账户启用
                .andNotExpiredEqualTo(true)//账户未过期
                .andCredentialsNotExpiredEqualTo(true);//凭证未过期
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        log.info("sysuser-log > [{}] [{}]",this.getClass().getName());
        return sysUsers.size() > 0 ? sysUsers.get(0) : null;
    }

    /**
     * 分页查询数据
     * @param page
     * @return
     */
    public HttpResult findPageList(Page page) {
        int currentPage = page.getCurrentPage();
        Integer pageCounts = page.getPageCounts();
        int first = (currentPage - 1) * pageCounts;

        List<SysUser> lists = sysUserMapper.findPageList(first, pageCounts);
        page.getData().put(HttpResult.LIST_TAG, lists);// 当前页面数据

        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteStatusEqualTo(GlobalConstant.DELETE_STATUS_NOT_DELETE);//delete_status='0' 的数据

        List<SysUser> list1 = sysUserMapper.selectByExample(example);//不分页总数据
        page.setTotalCounts(list1.size());
        return HttpResult.success().add(HttpResult.PAGE_TAG, page);
    }

    /**
     * 创建新用户 并分配 好岗位
     * @param sysUser 新增用户
     * @param postId 岗位ID
     * @return
     */
    public HttpResult createAndBuildPostDeptRelation(SysUser sysUser, Integer postId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(sysUser.getDeptId());
        sysUser.setDeptName(sysDept.getDeptName());//部门信息
        int i = sysUserMapper.insertSelective(sysUser);
        Integer userId = sysUser.getUserId();
        if (userId != null) {
            //新用户 创建 岗位关联
            if (postId != null) {
                sysPostMapper.insertUserPostRelation(userId, postId);
            }
            //新用户 创建 部门关联
            sysDeptMapper.insertUserDeptRelation(userId, sysUser.getDeptId());
        }
        return HttpResult.success();
    }

    /**
     * 查询用户是否存在, 查询 delete_status = '0' 或 '1' 的用户
     * @param username
     * @return
     */
    public boolean checkUsernameExist(String username) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        return sysUsers.size() > 0 ? true : false;
    }

    /**
     * 修改上回登录信息
     * @param sysUser
     * @return
     */
    public int updateLoginDateAndLoginIpByUsername(SysUser sysUser) {
        int i = sysUserMapper.updateLoginDateAndLoginIpByUsername(sysUser);
        return i;
    }

    /**
     * 批量删除用户,并更新用户的修改时间及修改人字段
     * @param userids
     * @param username
     * @return
     */
    public HttpResult updateDeleteStatusByIds(List<Integer> userids, String username) {
        int i = sysUserMapper.updateDeleteStatusByIds(userids, username, GlobalConstant.DELETE_STATUS_DELETE);
        return HttpResult.success();
    }

    /**
     * 修改用户信息, 并重新 建立 用户与部门  用户与岗位 的关联关系
     * @param sysUser
     * @param postId
     * @return
     */
    public HttpResult updateAndReBuildPostDeptRelation(SysUser sysUser, Integer postId) {
        SysUser sysUserDb = sysUserMapper.selectByPrimaryKey(sysUser.getUserId());
        if (sysUser.getDeptId() != null) {
            SysDept sysDept = sysDeptMapper.selectByPrimaryKey(sysUser.getDeptId());
            sysUser.setDeptName(sysDept.getDeptName());
        }
        Integer userId = sysUser.getUserId();
        //与 部门 重新建交
        List<SysDept> depts = sysDeptMapper.selectUserDeptRelationByUserId(userId);
        if (depts.size() > 0) {
            sysDeptMapper.deleteUserDeptRelationByUserId(userId);
        }
        sysDeptMapper.insertUserDeptRelation(userId, sysUser.getDeptId());
        //与 岗位 重新建交
        List<SysPost> posts = sysPostMapper.selectUserPostRelationByUserId(userId);
        if (posts.size() > 0) {
            sysPostMapper.deleteUserPostRelationByUserId(userId);
        }
        sysPostMapper.insertUserPostRelation(userId, postId);
        //更新User表
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return HttpResult.success();
    }

    /**
     * 给当前用户重新授予角色权限,先删除用户与角色关联(注意非标记删除),再重新创建新的关联。并且更新 userid 用户对应的修改人员和修改时间
     * @param userId
     * @param roleIds
     * @param username
     * @return
     */
    public int regrantUserRolesByLoginUser(Integer userId, List<Integer> roleIds, String username) {
        // 查询 sys_user_role 关联表中是否存在 与当前用户关联 的角色
        List<SysRole> roles = sysRoleMapper.findRolesByUserId(userId);
        // 如果存在关联则将其删除
        if (roles.size() > 0) {
            sysRoleMapper.deleteRolesByUserId(userId);
        }
        // 重新建立 用户与角色 的关联关系, 往 sys_user_role 中插入新的关联数据
        int updateCounts = sysRoleMapper.insertRolesByUserId(userId, roleIds);
        // 记录 userid 用户数据中的修改人员和修改时间
        sysUserMapper.updateUserUpdateAtAndUpdatebyByUserId(new SysUser(userId, username, new Date()));
        return updateCounts;
    }

    /**
     * 给用户初始化密码操作
     * @param sysUser
     * @return
     */
    public int initializePassword(SysUser sysUser) {
        return sysUserMapper.initializePassword(sysUser);
    }

    /**
     * 更新用户账号状态  启用 停用
     * @param sysUser
     * @return
     */
    public int updateUserStatus(SysUser sysUser) {
        return sysUserMapper.updateUserStatus(sysUser);
    }
}
